<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="back-button" @click="goBack">
          <i class="el-icon-arrow-left"></i>
          <span>返回列表</span>
        </div>
        <h2 class="title">{{ trainInfo.name }}</h2>
      </div>
    </div>

    <!-- 训练信息卡片 -->
    <el-row :gutter="20" class="info-section">
      <el-col :span="16">
        <el-card shadow="hover" class="info-card">
          <div class="card-header">
            <i class="el-icon-info"></i>
            <span>训练基本信息</span>
          </div>
          <div class="info-content">
            <!-- 左侧基本信息 -->
            <div class="basic-info">
              <div class="info-row">
                <div class="info-item">
                  <span class="label"><i class="el-icon-tickets"></i>训练类型</span>
                  <el-tag 
                    :type="getTrainTypeTag(trainInfo.type)" 
                    effect="dark" 
                    size="medium"
                  >
                    {{ getTrainTypeLabel(trainInfo.type) }}
                  </el-tag>
                </div>
                <div class="info-item">
                  <span class="label"><i class="el-icon-user"></i>参训年级</span>
                  <span class="value highlight">{{ trainInfo.grade }}级</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label"><i class="el-icon-time"></i>训练时间</span>
                  <span class="value">{{ trainInfo.time }}</span>
                </div>
                <div class="info-item">
                  <span class="label"><i class="el-icon-timer"></i>请假截止</span>
                  <span class="value">{{ trainInfo.overtime }}</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label"><i class="el-icon-location"></i>训练地点</span>
                  <span class="value">{{ trainInfo.address }}</span>
                </div>
                <div class="info-item">
                  <span class="label"><i class="el-icon-user-solid"></i>参训人数</span>
                  <span class="value highlight">{{ trainInfo.number }}人</span>
                </div>
              </div>
            </div>
            <!-- 训练内容区域 -->
            <div class="content-section">
              <div class="content-header">
                <i class="el-icon-document"></i>
                <span>训练内容</span>
              </div>
              <div class="content-body rich-text" v-html="trainInfo.content"></div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="card-header">
            <i class="el-icon-data-line"></i>
            <span>参训统计</span>
          </div>
          <div class="stats-content">
            <div class="stats-item">
              <div class="stats-value">{{ total }}</div>
              <div class="stats-label">参训总人数</div>
            </div>
            <el-divider></el-divider>
            <div class="stats-item">
              <div class="stats-value">{{ trainInfo.number }}</div>
              <div class="stats-label">实到人数</div>
            </div>
            <el-divider></el-divider>
            <div class="stats-value-chart">
              <div class="chart-title">参训率</div>
              <el-progress 
                type="circle" 
                :percentage="getAttendRate" 
                :stroke-width="10"
                :color="getProgressColor"
              ></el-progress>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 参训人员列表 -->
    <el-card class="player-card" shadow="hover">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-user"></i>
          <span>参训人员名单</span>
        </div>
        <div class="header-right">
          <el-radio-group v-model="listType" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="attend">已到</el-radio-button>
            <el-radio-button label="leave">请假</el-radio-button>
            <el-radio-button label="absent">缺勤</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 班级分组展示 -->
      <el-collapse v-model="activeClazz">
        <el-collapse-item 
          v-for="clazzUser in clazzUsers" 
          :key="clazzUser.clazz.clazzId" 
          :title="`${clazzUser.clazz.name} (班长：${clazzUser.clazz.leader})`"
          :name="clazzUser.clazz.clazzId"
        >
          <div class="player-list">
            <el-table :data="filterPlayersByType(clazzUser.users)" border>
              <el-table-column label="姓名" prop="nickName" align="center" />
              <el-table-column label="学号" prop="studentId" align="center" />
              <el-table-column label="联系方式" prop="phonenumber" align="center" />
              <el-table-column label="年级" prop="grade" align="center">
                <template slot-scope="scope">
                  {{ scope.row.grade }}级
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                  <el-tag :type="getStatusTag(scope.row.status)">
                    {{ getStatusLabel(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script>
import { trainToUser } from '@/api/manager/train/train'

export default {
  name: 'TrainDetail',
  dicts: ["train_type"],
  data() {
    return {
      // 训练信息
      trainInfo: {
        trainId: undefined,
        name: '',
        time: '',
        overtime: '',
        address: '',
        content: '',
        type: undefined,
        number: 0,
        grade: ''
      },
      // 参训人员列表
      playerList: [],
      // 当前展开的班级
      activeClazz: [],
      // 列表过滤类型
      listType: 'all',
      // 加载状态
      loading: false,
      clazzUsers: [], // 班级用户数据
      total: 0,      // 总人数
      trainTypeOptions: {
        0: '日常训练',
        1: '加训',
        2: '补训'
      }
    }
  },
  computed: {
    // 获取实到人数
    getAttendCount() {
      return this.playerList.filter(p => p.status === 1).length
    },
    // 计算参训率
    getAttendRate() {
      return this.total ? 
        Math.round((this.trainInfo.number / this.total) * 100) : 0
    },
    // 进度条颜色
    getProgressColor() {
      const rate = this.getAttendRate
      if (rate >= 90) return '#67C23A'
      if (rate >= 70) return '#E6A23C'
      return '#F56C6C'
    },
    // 按班级分组的人员列表 - 适配后端数据结构
    groupedPlayers() {
      const groups = []
      this.playerList.forEach(item => {
        const clazz = {
          clazzId: item.clazz.clazzId,
          clazzName: `${item.clazz.grade}级${item.clazz.name}`,
          leader: item.clazz.leader,
          phone: item.clazz.phone,
          players: item.users.map(user => ({
            playerName: user.nickName,
            studentId: user.studentId,
            phone: user.phonenumber,
            status: user.status === '0' ? 1 :   // 已到
                    user.status === '1' ? 0 :   // 请假
                    2,                          // 缺勤
            grade: user.grade
          }))
        }
        groups.push(clazz)
      })
      return groups
    }
  },
  // 添加路由导航守卫
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重置数据
      vm.resetData()
      // 获取路由参数并初始化数据
      const query = to.query
      vm.trainInfo = {
        trainId: parseInt(query.trainId) || 0,
        name: query.name,
        time: query.time,
        overtime: query.overtime,
        address: query.address,
        content: query.content,
        type: query.type,
        number: query.number,
        grade: query.grade
      }
      // 重新获取数据
      vm.getPlayerList()
    })
  },
  methods: {
    // 添加重置数据方法
    resetData() {
      this.trainInfo = {
        trainId: undefined,
        name: '',
        time: '',
        overtime: '',
        address: '',
        content: '',
        type: undefined,
        number: 0,
        grade: ''
      }
      this.playerList = []
      this.activeClazz = []
      this.listType = 'all'
      this.loading = false
    },
    // 获取参训人员列表
    getPlayerList() {
      if (!this.trainInfo.trainId) {
        this.$modal.msgError("训练ID不能为空");
        return;
      }
      this.loading = true;
      trainToUser(this.trainInfo).then(response => {
        if (response.code === 200) {
          const { clazzUsers, total } = response.data;
          this.clazzUsers = clazzUsers;
          this.total = total;
          // 默认展开第一个班级
          if (this.clazzUsers.length) {
            this.activeClazz = [this.clazzUsers[0].clazz.clazzId];
          }
          // 更新实到人数
          this.updateStats();
        } else {
          this.$modal.msgError(response.msg || "获取参训人员失败");
          this.clazzUsers = [];
        }
      }).catch(() => {
        this.clazzUsers = [];
        this.$modal.msgError("获取参训人员失败");
      }).finally(() => {
        this.loading = false;
      });
    },
    // 返回列表页
    goBack() {
      this.$router.go(-1)
    },
    // 获取训练类型标签样式
    getTrainTypeTag(type) {
      const typeMap = {
        0: 'primary',  // 日常训练 - 蓝色
        1: 'success',  // 加训 - 绿色
        2: 'warning'   // 补训 - 黄色
      }
      return typeMap[type] || 'info'
    },
    // 获取状态标签类型
    getStatusTag(status) {
      const statusMap = {
        '0': 'success',  // 已到
        '1': 'warning',  // 请假
        '2': 'danger'    // 缺勤
      }
      return statusMap[status] || 'info'
    },
    // 获取状态标签文本
    getStatusLabel(status) {
      const statusMap = {
        '0': '已到',
        '1': '请假',
        '2': '缺勤'
      }
      return statusMap[status] || '未知'
    },
    // 修改过滤方法
    filterPlayersByType(users) {
      if (this.listType === 'all') return users
      
      const statusMap = {
        'attend': '0',  // 已到
        'leave': '1',   // 请假
        'absent': '2'   // 缺勤
      }
      
      return users.filter(user => user.status === statusMap[this.listType])
    },
    // 获取训练详情数据
    getTrainDetails() {
      trainToUser({ trainId: this.trainId }).then(response => {
        const { clazzUsers, total } = response.data
        this.clazzUsers = clazzUsers
        this.total = total
        // 更新统计数据
        this.updateStats()
      })
    },
    // 更新统计数据
    updateStats() {
      let attendCount = 0;
      this.clazzUsers.forEach(clazzUser => {
        clazzUser.users.forEach(user => {
          if(user.status === '0') { // 已到
            attendCount++;
          }
        });
      });
      this.trainInfo.number = attendCount;
    },
    // 添加获取训练类型标签的方法
    getTrainTypeLabel(type) {
      return this.trainTypeOptions[type] || '未知类型'
    },
  }
}
</script>

<style lang="scss" scoped>
.page-header {
  background: #fff;
  padding: 16px 24px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

  .header-content {
    display: flex;
    align-items: center;

    .back-button {
      display: flex;
      align-items: center;
      cursor: pointer;
      color: #409EFF;
      margin-right: 20px;

      i {
        margin-right: 5px;
      }

      &:hover {
        opacity: 0.8;
      }
    }

    .title {
      margin: 0;
      font-size: 20px;
      color: #303133;
      font-weight: 600;
    }
  }
}

.info-section {
  margin-bottom: 20px;
}

.info-card, .stats-card {
  height: 100%;

  .card-header {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: bold;
    color: #303133;

    i {
      margin-right: 8px;
      color: #409EFF;
    }
  }
}

.info-content {
  .info-item {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      display: inline-block;
      width: 100px;
      color: #909399;
    }

    .value {
      color: #303133;
    }

    &.content {
      .value {
        margin-top: 10px;
        line-height: 1.6;
      }
    }
  }
}

.stats-content {
  text-align: center;

  .stats-item {
    padding: 15px 0;

    .stats-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 8px;
    }

    .stats-label {
      font-size: 14px;
      color: #909399;
    }
  }

  .stats-value-chart {
    padding: 20px 0;

    .chart-title {
      margin-bottom: 15px;
      font-size: 14px;
      color: #909399;
    }
  }
}

.player-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      i {
        margin-right: 8px;
        color: #409EFF;
      }

      span {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .player-list {
    margin: 10px 0;
  }
}

::v-deep {
  .el-collapse-item__header {
    font-size: 15px;
    font-weight: bold;
  }

  .el-table {
    margin: 10px 0;
  }
}

.info-card {
  .info-content {
    .basic-info {
      padding: 20px;
      background: #f8f9fb;
      border-radius: 8px;
      margin-bottom: 24px;

      .info-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .info-item {
          flex: 1;
          padding: 0 15px;

          .label {
            display: block;
            color: #909399;
            margin-bottom: 8px;
            font-size: 13px;

            i {
              margin-right: 4px;
              font-size: 14px;
            }
          }

          .value {
            font-size: 14px;
            color: #303133;

            &.highlight {
              color: #409EFF;
              font-weight: bold;
              font-size: 16px;
            }
          }

          .el-tag {
            padding: 0 12px;
            height: 28px;
            line-height: 26px;
          }
        }
      }
    }

    .content-section {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

      .content-header {
        margin-bottom: 16px;
        padding-bottom: 16px;
        border-bottom: 1px solid #EBEEF5;
        color: #303133;
        font-weight: bold;

        i {
          margin-right: 8px;
          color: #409EFF;
        }
      }

      .content-body {
        min-height: 100px;
        line-height: 1.8;
        color: #606266;
        
        ::v-deep {
          p {
            margin: 0;
            padding: 4px 0;
          }
        }
      }
    }
  }
}
</style>
